﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using MediaArtAggregator.Core.Configuration;
using CCNetConfig.BugTracking.Configuration.Handlers;
using System.Xml;
using CCNetConfig.BugTracking;

namespace MediaArtAggregator {
  static class Program {
    private static BugTracker _bugTracker = null;

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main ( ) {
      try {
        Application.SetUnhandledExceptionMode ( UnhandledExceptionMode.CatchException, false );
      } catch { }

      AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler ( Program.OnUnhandledException );

      SettingsFile = new FileInfo ( Path.Combine ( Application.StartupPath, "configuration.xml" ) );
      Application.EnableVisualStyles ( );

      Application.SetCompatibleTextRenderingDefault ( false );
      try {
        Application.Run ( new MainForm ( ) );
      } catch ( Exception ex ) {
        Program.BugTracker.SubmitExceptionDialog ( null, ex, ( FileInfo ) null );
      }
    }
    private static Settings _settings = null;

    public static FileInfo SettingsFile { get; set; }

    public static Settings Settings {
      get {
        if ( _settings == null ) {
          _settings = Settings.Load ( Program.SettingsFile );
        }
        return _settings;
      }
    }

    private static void OnUnhandledException ( object sender, UnhandledExceptionEventArgs e ) {
      Exception ex = e.ExceptionObject as Exception;
      Program.BugTracker.SubmitExceptionDialog ( null, ex,(FileInfo)null );
    }

    public static BugTracker BugTracker {
      get {
        if ( _bugTracker == null ) {
          BugTrackingConfigurationSectionHandler btcsh = new BugTrackingConfigurationSectionHandler ( );
          XmlDocument bugTrackerDoc = new XmlDocument ( );
          bugTrackerDoc.Load ( Path.Combine ( Application.StartupPath, "BugTracking.config" ) );
          _bugTracker = btcsh.Create ( null, null, bugTrackerDoc.DocumentElement );
        }
        return _bugTracker;
      }
    }

  }
}
